<template>
  <div class='echart' ref='echart'>
    <div class='echarts' ref='echarts' res='chart' />
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  props: {
    echartData: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {
      myChart: null
    }
  },
  methods: {
    subStr (str) {
      let newstr = ''
      if (str.length > 8) {
        newstr = str.slice(0, 8) + '\n'
        return newstr + this.subStr(str.slice(8))
      } else {
        return str
      }
    },
    initChart () {
      let Then = this
      const chartDom = this.$refs.echarts
      this.myChart = echarts.init(chartDom)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '0%',
          right: '0%',
          bottom: '10%',
          containLabel: true
        },
        dataZoom: [
          {
            type: 'inside',
            xAxisIndex: 0,
            startValue: 0,
            endValue: 2,
            zoomLock: true
          }
        ],
        xAxis: [
          {
            data: this.echartData.label || [],
            // axisLabel: {
            //   interval: 0
            // },
            axisLabel: {
              interval: 0,
              // rotate: 90,
              // margin: 10,
              fontSize: this.xAxisFontSize,
              // x轴竖着显示
              formatter (v) {
                return Then.subStr(v)
              }
            },
            axisTick: {
              alignWithLabel: false
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            // name: 'Direct',
            type: 'bar',
            barWidth: '50%',
            data: this.echartData.value || []
          }
        ]
      }
      if (option && chartDom && this.echartData.label.lenght !== 0) {
        this.myChart.setOption(option)
        this.myChart.resize()
      } else {
        chartDom.innerHTML = ''
        chartDom.removeAttribute('_echarts_instance_')
      }
    }
  },
  mounted () {
    this.initChart()
    window.addEventListener('resize', () => {
      this.myChart.resize()
    })
  },
  watch: {
    echartData: {
      deep: true,
      handler () {
        this.initChart()
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.echart {
  height: 100%;
}
.echarts {
  color: #0e521a;
  min-width: 100%;
  height: 100%;
}
</style>
